﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PessModel;
using PessMvc.Lib;
using PessMvc.Models;
using System.Web.Security;
using LinqKit;

namespace PessMvc.Controllers
{
    [Authorize]
    public class AuthorController : Controller
    {
        private PESSEntities db = new PESSEntities();
        IAuthorBL ibl;

        public AuthorController()
        {
             ibl= new AuthorBL();
        }

        // GET: /Author/
        [Authorize(Roles="Admin")]
        public ActionResult Index(string errorMessage="")
        {
            ViewBag.ErrorMessage = errorMessage;
            return View(db.Authors.OrderBy(a=>a.SerialNumber).ToList());
        }

        //
        // GET: /Author/Details/5

        //public ActionResult Details(string id = null)
        //{
        //    Author author = db.Authors.Find(id);
        //    if (author == null)
        //    {
        //        return HttpNotFound();
        //    }
        //    return View(author);
        //}

        //
        // GET: /Author/Create
        [Authorize(Roles="Admin")]
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Author/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(AuthorModel author)
        {
            if (ModelState.IsValid)
            {
                
                string errorMessage="";
                if (ibl.Add(author, out errorMessage))
                {
                    return RedirectToAction("Index");
                }
                else
                {
                    ModelState.AddModelError("", errorMessage);
                }
              
            }

            return View(author);
        }

        //
        // GET: /Author/Edit/5

        public ActionResult Edit(string returnUrl,string authorSN="")
        {
            Author author = null;
            if (Roles.IsUserInRole(Membership.GetUser().UserName, "Author"))
            {
                author = ibl.Find(Membership.GetUser().UserName);
            }
            if (Roles.IsUserInRole(Membership.GetUser().UserName, "Admin")&&!String.IsNullOrEmpty(authorSN))
            {
                author = ibl.Find(authorSN);
            }
            if (author == null)
            {
                return HttpNotFound();
            }
            ViewBag.ReturnUrl=returnUrl;
            return View(author);
        }

        //
        // POST: /Author/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        [Authorize(Roles="Author,Admin")]
        public ActionResult Edit(Author author,string returnUrl="")
        {
            if (ModelState.IsValid)
            {
                if (Roles.IsUserInRole(Membership.GetUser().UserName, "Author"))
                {
                    author.SerialNumber = Membership.GetUser().UserName;//In case someone is trying to change other's info.
                }
                db.Entry(author).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                if(Roles.IsUserInRole(Membership.GetUser().UserName, "Admin"))
                {
                    return RedirectToAction("Index");                
                }
                else//which means user is an author
                {
                    return Go2ReturnUrl(returnUrl);
                }
            }
            return View(author);
        }

        public ActionResult Go2ReturnUrl(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Activity");
            }
        }
        //
        // GET: /Author/Delete/5
        [Authorize(Roles="Admin")]
        public ActionResult Delete(string authorSN = null)
        {
            Author author = db.Authors.Find(authorSN);
            if (author == null)
            {
                return HttpNotFound();
            }
            return View(author);
        }

        //Reset passwords for authors.
        [HttpPost,Authorize(Roles="Admin")]
        public ActionResult ResetPassword(List<AuthorSelectModel> authors, string password)
        {
            if (password.Trim().Length >= 3)
            {
                //string[] selectedExpertSNList = Request["ExpertSN"].Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                authors = authors.Where(a => a.IsSelected).ToList();
                foreach (var au in authors)
                {
                    //ExpertJudge expert = db.ExpertJudges.Find(sn);
                    var user = Membership.GetUser(au.SerialNumber);
                    user.UnlockUser();
                    string oldpsw = user.ResetPassword();
                    user.ChangePassword(oldpsw, password);
                }
                return RedirectToAction("Index", "Author");
            }
            else
            {
                return RedirectToAction("Index", "Author", new { errorMessage = "密码不能小于3个字符！" });
            }
        }

        //
        // POST: /Author/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Authorize(Roles = "Admin")]
        public ActionResult DeleteConfirmed(string serialNumber)
        {
            Author author = db.Authors.Find(serialNumber);
            if (author.Archives.Count>0)
            {
                ModelState.AddModelError("", string.Format("该用户已经上传{0}个文档，不能删除！",author.Archives.Count));
                return View(author);
            }
            else
            {
                if (Membership.GetUser(serialNumber) != null && !Membership.DeleteUser(serialNumber))
                {
                    ModelState.AddModelError("", "该用户无法删除！请联系系统管理员。");
                }
                else
                {
                    author.ActivityACLs.ForEach(c => c.Activity.ActivityACLs.Remove(c));
                    db.Authors.Remove(author);
                    db.SaveChanges();
                }
                
            }
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}